import Layout from '@/layout'
import { int2Bool } from './util'

/**
 * 路由权限验证
 * @param {*} authId 路由权限id
 * @param {*} role 用户角色
 * @returns 
 */
export const hasPermission = (authId, role) => {
  if (role.is_super == 1) return true
  if (Array.isArray(role.authIds) && role.authIds.length) {
    return role.authIds.indexOf(authId.toString()) != -1
  }
  return false
}

/**
 * 递归动态生成异步路由
 * @param {*} routes 后台路由表文件
 * @returns 
 */
export const generateAsyncRoutes = (routes) => {
  const asyncRoutes = []

  routes.forEach(route => {
    const currentRoute = {
      path: route.menu_path,
      name: route.menu_component_name,
      meta: {
        title: route.menu_title, 
        icon: route.menu_icon, 
        authId: route.id,
        activeMenu: route.menu_active,
        noCache: !int2Bool(route.menu_component_cache),
        breadcrumb: int2Bool(route.breadcrumb),
        affix: int2Bool(route.affix),
      },
      props: int2Bool(route.menu_props),
      hidden: int2Bool(route.menu_hidden),
    }
    // 如果有子级
    if (route.children && route.children.length) {
      currentRoute.component = Layout
      currentRoute.redirect = route.menu_redirect
      currentRoute.alwaysShow = int2Bool(route.always_show)
      currentRoute.children = generateAsyncRoutes(route.children)
    } else {
      currentRoute.component = resolve => require([`@/views${route.menu_component_path}`], resolve)
    }

    asyncRoutes.push(currentRoute)
  });

  return asyncRoutes
}